/* eslint-disable */
/**
 *
 * http配置
 * 
 */
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from '../store'
import Router from './router'

import {
    getToken,
    setToken,
    removeToken
} from '@/util/auth';

axios.defaults.timeout = 10000;
//跨域请求，允许保存cookie
//axios.defaults.withCredentials = true;
NProgress.configure({
    showSpinner: false
}) // NProgress Configuration
const requestMap = new Map();
//HTTPrequest拦截
axios.interceptors.request.use(config => {
    const keyString = JSON.stringify(Object.assign({}, {
        url: config.url,
        method: config.method
    }, config.data));
    if (requestMap.get(keyString)) {
        return Promise.reject('Please slow down a little')
    }
    requestMap.set(keyString, true);
    config = Object.assign(config, {
        _keyString: keyString
    });
    //NProgress.start() // start progress bar
    config.headers['Content-Type'] = 'application/json'
    if (store.getters.token) {
        config.headers['Authorization'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    return config
}, error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
})
//HTTPresponse拦截
axios.interceptors.response.use(res => {
    //NProgress.done();
    // 重置requestMap
    const config = Object.assign(res.config);
    requestMap.set(config._keyString, false);

    var token = res.headers.Authorization
    //console.log(res)
    if (token) {
        // 如果 header 中存在 token，那么触发 refreshToken 方法，替换本地的 token
        setToken('Bearer '+token)
        console.log('替换了token')
    }

    //如果返回statu为2的时候，退出登陆
    if (res.data.status == 2) {
        console.log(res)
        console.log('需要重新登陆')
        store.dispatch("LogOut").then(() => {
            Router.push({
                path: "/"
            });
        });
        return Promise.reject();
    }

    return res
}, error => {
    
    return Promise.reject(new Error(error));
})

export default axios